﻿using LmgCMS.Model;
using LmgCMS.Service;
using Microsoft.AspNetCore.Mvc;

namespace LmgCMS.Areas.API.Controllers {
    /// <summary>
    /// 组织机构
    /// </summary>
    public class OrganizeController : BaseController<Organize>
    {
        private readonly IOrganizeService _organizeService;
        public OrganizeController(IOrganizeService organizeService)
        {
            _organizeService = organizeService;
        }
        [HttpGet]
        public IActionResult GetTreeSelectJson()
        {
            var data = _organizeService.FindAll();
            var treeList = new List<TreeViewModel>();
            foreach (Organize item in data)
            {
                TreeViewModel treeModel = new TreeViewModel();
                treeModel.id = item.ID;
                treeModel.text = item.Name;
                treeModel.parentId = item.ParentID;
                treeModel.data = item;
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeSelectJson());
        }
        [HttpGet]
        public override IActionResult GetTreeJson()
        {
            var data = _organizeService.FindAll().ToList();
            var treeList = new List<TreeViewModel>();
            for (int i = 0; i < data.Count; i++)
            {
                Organize item = data[i];
                TreeViewModel tree = new TreeViewModel();
                bool hasChildren = data.Count(t => t.ParentID == item.ID) == 0 ? false : true;
                tree.id = item.ID;
                tree.text = item.Name;
                tree.value = item.ID;
                tree.parentId = item.ParentID;
                tree.isexpand = i <= 1 ? true : false;
                tree.complete = true;
                tree.checkstate = i == 0 ? 1 : 0;
                tree.hasChildren = hasChildren;
                treeList.Add(tree);
            }
            return Content(treeList.TreeViewJson());
        }


        [HttpGet]
        public IActionResult GetGridDataJson(string pId, [FromForm] Paging paging)
        {
            System.Text.StringBuilder strWhere = new System.Text.StringBuilder();
            strWhere.Append(" 1=1 ");
            if (!string.IsNullOrWhiteSpace(pId))
            {
                strWhere.Append(" AND (ParentID='" + pId + "' OR ID='" + pId + "') ");
            }
            if (!string.IsNullOrWhiteSpace(paging.keyword))
            {
                strWhere.Append(" AND Name like '%" + paging.keyword + "%' ");
            }
            paging.sqlwhere = strWhere.ToString();
            return base.GetJGridPageDataJson(paging);
        }
    }
}